//
//  SearchVC.swift
//  NewXueBa
//
//  Created by Shine on 2019/6/6.
//  Copyright © 2019 jmxQAQ. All rights reserved.
//

import UIKit

class SearchVC: BCBaseVC {

    let headeeViewH: CGFloat = 30 // 区头的高度

    @IBOutlet weak var searchText: UITextField!
    @IBOutlet weak var searchTab: UITableView!
    
    private var typeVersion = 1
    private let vm = CourseVM()
    private let disposeBag = DisposeBag()
    
    var courseType:CourseType  = .AwaitClasss
    var proView: BCProtocolView? // 协议的无数据view

    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        searchTextSignal()
        observeLoadData()
    }
    
    @IBAction func cancleClick(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    // 参数配置 界面配置
    fileprivate func setUI() {
        if courseType == .AwaitClasss {
            typeVersion = 1
        } else if courseType == .LookBackClass {
            typeVersion = 0
        }
        self.fd_prefersNavigationBarHidden = true
        searchTab.rowHeight = 152
    }
    
    /*
     搜索框的信号的逻辑 触发
     */
    fileprivate func searchTextSignal() {
        let searchTextOb = searchText.rx.text.orEmpty
            .throttle(0.3, scheduler: MainScheduler.instance)
            .distinctUntilChanged()
            .flatMapLatest { inputTest -> Observable<[String : [Course_list]]> in
                return self.vm.search_pages(self.typeVersion, inputTest).asObservable()
                           .observeOn(MainScheduler.instance)
                           .catchErrorJustReturn([String:[Course_list]]())
            }
            .share(replay: 1, scope: .forever)
        // 信号链没有被观察的 不会去自发的去释放信号 自由被观察了  才会去不断释放
        // 所以此处作用，让信号链持续工作，并无具体逻辑意义
        searchTextOb.map { $0.count > 0 }
            .bind(to: BCUIButton().ex_loginBtnState)
            .disposed(by: disposeBag)
    }
    
    // 监控数据 加载刷新
    fileprivate func observeLoadData() {
        vm.resultData.asObservable()
            .subscribe({ [weak self](resultData) in
                self?.searchTab.reloadData()
                self?.setProView(dataCount: self?.vm.mdArray.count ?? 0)
            }).disposed(by: disposeBag)
    }
    
}

extension SearchVC: BCVCDataNetPro {
    /// 无数据加载
    ///
    /// - Parameter dataCount: 数据数目
    fileprivate func setProView(dataCount: NSInteger) {
        
        if  proView == nil {
            let y = bcTopBarHeight + 50
            let h = kScreenHeight - y - bcTabBarHeight
            let frame = CGRect(x: 0, y: y, width: kScreenWidth, height: h)
            proView = loadBCProViewInVC(image: UIImage(named: "icon_search"), alertText: "没找到搜索内容", frame: frame) //初始化协议view
            proView?.proImageV?.bounds = CGRect(x: 0, y: 0, width: 100, height: 100)
        }
        
        if dataCount == 0 , searchText.text?.count ?? 0 > 0 {
            // 有搜索 无数据
            proView?.isHidden = false
        } else {
            proView?.isHidden = true
        }
        
    }
}

extension SearchVC: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let list = vm.resultData.value[vm.mdArray[section]]
        return list?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "AwaitClassCell") as! AwaitClassCell
        cell.courseType = self.courseType
        let list = vm.resultData.value[vm.mdArray[indexPath.section]]
        let model = list?[indexPath.row]
        cell.awaitModel = model
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return vm.mdArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return headeeViewH
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headview = UIView()
        headview.backgroundColor = UIColor.hex(hexString: "#F8F8F8")
        headview.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: headeeViewH)
        let labe = UILabel()
        labe.frame = CGRect(x: 15, y: 7, width: 200, height: 16)
        labe.textAlignment = .left
        let nowTime = String.getNowTimeString(format: .TimeType_Md)
        if vm.mdArray[section] == nowTime {
            labe.text = "今天"
        } else {
            labe.text = vm.mdArray[section]
        }
        headview.addSubview(labe)
        return headview
    }
}
